<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 对象 用来描述一个物体或整体的内容 用{}创建对象-->方式1
        let person = {
            // 属性名：属性值(数据，基本类型数据-引用类型数据)
            name: '张三',
            gender: '男',
            age: '18',
            isSingle: true,
            hobby: ['篮球', '足球', '乒乓球'],
            possession: {
                car: false,
                house: false,
                money: 10,
            }
        }
        // 对象的访问  对象.属性名
        console.log("姓名", person.name);
        console.log("性别", person.gender);
        console.log("年龄", person.age);
        // 访问对象中的数组
        console.log("爱好", person.hobby[0], person.hobby[1], person.hobby[2]);
        // 访问对象中的对象
        console.log("车", person.possession.car);
        console.log("房子", person.possession.house);
        console.log("钱", person.possession.money);

        // 易错点
        // console.log(person.name1); // undefined 不存在name1属性
        // console.log(person1.age); // undefined 不存在person1对象

        // console.log(person.hobby1[2]); //报错 Cannot read properties of undefined (reading '2')

        // console.log(person.possession1.money); // 报错 Cannot read properties of undefined (reading 'money')


        //创建对象-->方式2 new Object()
        let person1 = new Object();
        person1.name = '李四';
        person1.gender = '男';
        person1.age = '18';
        person1.isSingle = true;
        person1.hobby = ['篮球', '足球', '乒乓球'];
        person1.possession = {
            car: false,
            house: false,
            money: 10,
        }
        console.log("姓名", person1.name, "性别", person1.gender, "年龄", person1.age, "爱好", person1.hobby[0], person1.hobby[1], person1.hobby[2], "车", person1.possession.car, "房子", person1.possession.house, "钱", person1.possession.money);


        //使用函数来构造对象
        function Person(name, gender, age, isSingle, hobby, possession) {
            this.name = name;
            this.gender = gender;
            this.age = age;
            this.isSingle = isSingle;
            this.hobby = hobby;
            this.possession = possession;
            this.changeName = changeName;
            function changeName(lastName) {
                this.name = lastName;
            }
        }
        let person2 = new Person('张三', '男', 18, true, '看电影', '手机');
        document.write(`姓名：${person2.name}<br>性别：${person2.gender}<br>年龄：${person2.age}<br>是否单身：${person2.isSingle}<br>爱好：${person2.hobby}<br> possessions：${person2.possession}`);
        person2.changeName('王五');
        document.write(`<br>姓名：${person2.name}`)

        // for...in 遍历对象属性
        for (let x in person1) {
            document.write(`<br>${x}:${person1[x]}`);
        }
    </script>
</body>

</html>